import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { transactionDB } from '@/utils/database'
import type { Transaction, ApiResponse } from '@/types'
import { showToast } from 'vant'

export const useTransactionStore = defineStore('transaction', () => {
  // 状态
  const transactions = ref<Transaction[]>([])
  const loading = ref(false)
  const currentPage = ref(1)
  const totalPages = ref(1)
  const totalItems = ref(0)

  // 计算属性
  const totalIncome = computed(() => {
    return transactions.value
      .filter(t => t.type === 'income')
      .reduce((sum, t) => sum + t.amount, 0)
  })

  const totalExpense = computed(() => {
    return transactions.value
      .filter(t => t.type === 'expense')
      .reduce((sum, t) => sum + t.amount, 0)
  })

  const balance = computed(() => totalIncome.value - totalExpense.value)

  // 获取交易记录列表
  const fetchTransactions = async (params?: any) => {
    try {
      loading.value = true
      const response: any = await transactionDB.getAll(params)

      if (response.status === 'success' && response.data) {
        transactions.value = response.data.transactions
        // 离线模式下简化分页
        totalItems.value = response.data.total || 0
      }
    } catch (error) {
      console.error('获取交易记录失败:', error)
      showToast('获取交易记录失败')
    } finally {
      loading.value = false
    }
  }

  // 创建交易记录
  const createTransaction = async (data: Omit<Transaction, 'id'>) => {
    try {
      loading.value = true
      const response: any = await transactionDB.create(data)

      if (response.status === 'success' && response.data) {
        // 重新获取列表以确保数据同步
        await fetchTransactions()
        showToast('添加成功')
        return response.data
      }
    } catch (error) {
      console.error('创建交易记录失败:', error)
      showToast('添加失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新交易记录
  const updateTransaction = async (id: number, data: Partial<Transaction>) => {
    try {
      loading.value = true
      const response: any = await transactionDB.update(id, data)

      if (response.status === 'success' && response.data) {
        const index = transactions.value.findIndex(t => t.id === id)
        if (index !== -1) {
          transactions.value[index] = { ...transactions.value[index], ...response.data }
        }
        showToast('更新成功')
        return response.data
      }
    } catch (error) {
      console.error('更新交易记录失败:', error)
      showToast('更新失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除交易记录
  const deleteTransaction = async (id: number) => {
    try {
      loading.value = true
      const response: any = await transactionDB.delete(id)

      if (response.status === 'success') {
        const index = transactions.value.findIndex(t => t.id === id)
        if (index !== -1) {
          transactions.value.splice(index, 1)
        }
        showToast('删除成功')
        return true
      }
    } catch (error) {
      console.error('删除交易记录失败:', error)
      showToast('删除失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 重置状态
  const reset = () => {
    transactions.value = []
    currentPage.value = 1
    totalPages.value = 1
    totalItems.value = 0
  }

  return {
    // 状态
    transactions,
    loading,
    currentPage,
    totalPages,
    totalItems,
    
    // 计算属性
    totalIncome,
    totalExpense,
    balance,
    
    // 方法
    fetchTransactions,
    createTransaction,
    updateTransaction,
    deleteTransaction,
    reset
  }
})